<template>
  <div>
    <!-- 操作栏 -->
    <div style="margin-bottom: 12px;">
      <el-button-group>
        <el-button
          v-for="(label, key) in dataFields"
          :key="key"
          size="mini"
          :type="currentField === key ? 'primary' : 'default'"
          @click="selectField(key)"
        >
          {{ label }}
        </el-button>
      </el-button-group>

      <el-button-group style="margin-left: 10px;">
        <el-button
          v-for="(label, days) in dateRanges"
          :key="days"
          size="mini"
          :type="isQuickRangeActive(Number(days)) ? 'success' : 'default'"
          @click="changeDateRange(Number(days))"
        >
          {{ label }}
        </el-button>
      </el-button-group>

      <el-date-picker
        v-model="customRange"
        type="daterange"
        size="mini"
        unlink-panels
        style="margin-left: 12px; width: 260px;"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="{ disabledDate: time => time.getTime() > Date.now() }"
        @change="onCustomRangeChange"
      />

      <el-button type="primary" size="mini" @click="toggleChartType" style="margin-left: 40px;">
        切换为{{ chartType === 'line' ? '柱状图' : '折线图' }}
      </el-button>

      <el-button size="mini" type="primary" @click="showProductDialog = true" style="margin-left: 20px;">
        选择展示产品 (已选 {{ selectedProducts.length }}/{{ ourProductList.length + competeProductList.length }})
      </el-button>
    </div>

    <div>
      <ECharts :options="chartOptions" autoresize style="width: 95%; height: 65vh;" />
    </div>

    <div style="text-align: center; padding-top: 10px;">
      <small>数据日期范围：{{ dateRangeTip }}</small>
    </div>

    <!-- 产品选择弹窗 -->
    <el-dialog title="选择要展示的产品" :visible.sync="showProductDialog" :modal="false" width="40%">
      <div style="margin-bottom: 12px;">
        已选 {{ selectedProducts.length }} / {{ ourProductList.length + competeProductList.length }}
      </div>

      <div style="max-height: 300px; overflow-y: auto;">
        <div style="font-weight: bold;">我们的产品</div>
        <el-checkbox-group v-model="selectedProducts">
          <el-checkbox v-for="item in ourProductList" :key="item.label" :label="item.label">
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>

        <div style="font-weight: bold; margin-top: 12px;">竞品</div>
        <el-checkbox-group v-model="selectedProducts">
          <el-checkbox v-for="item in competeProductList" :key="item.label" :label="item.label">
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>

      <template #footer>
        <el-button @click="showProductDialog = false">取消</el-button>
        <el-button type="primary" @click="onConfirmProductSelection">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import ECharts from 'vue-echarts';

export default {
  name: 'MultiMetricChart',
  components: { ECharts },
  props: {
    props_data: {
      default: () => ({})
    }
  },
  data() {
    return {
      chartType: 'line',
      chartOptions: {},
      all_data: {},
      dateRangeTip: '',
      selectedDays: 7,
      currentField: 'sales',
      customRange: null,
      ourProductList: [],
      competeProductList: [],
      selectedProducts: [],
      showProductDialog: false,
      chartData: [],
      dataFields: {
        sales: '销量',
        gmv: '销售额',
        price: '单价'
      },
      dateRanges: {
        7: '最近7天',
        15: '最近15天',
        30: '最近30天'
      }
    };
  },
  beforeMount() {
    this.$http('get', `/MapCompeteListing/details/${this.props_data.id}`, this.props_data).then(res => {
      const our_list = (res.data.our_listing || []).map(item => ({
        label: item.paltfrom_sku + '--' + item.listing_id,
        type: 'our'
      }))
      const compete_list = (res.data.compete_listing || []).map(item => ({
        label: '竞品--' + item.listing_id,
        type: 'compete'
      }))

      this.ourProductList = our_list
      this.competeProductList = compete_list

      const defaultOur = our_list.slice(0, 3).map(i => i.label)
      const defaultCompete = compete_list.slice(0, 1).map(i => i.label)
      this.selectedProducts = [...defaultOur, ...defaultCompete]

      this.all_data = res.data
      this.generateMockData(this.selectedDays)
    })
  },
  methods: {
    toggleChartType() {
      this.chartType = this.chartType === 'line' ? 'bar' : 'line';
      this.updateEchart();
    },
    selectField(field) {
      this.currentField = field;
      this.updateEchart();
    },
    changeDateRange(days) {
      this.selectedDays = days;
      this.customRange = null;
      this.generateMockData(days);
    },
    isQuickRangeActive(days) {
      return this.selectedDays === days && this.customRange === null;
    },
    onCustomRangeChange(range) {
      if (!range || range.length !== 2) return;
      const [start, end] = range;
      this.generateMockData(0, start, end);
    },
    onConfirmProductSelection() {
      this.showProductDialog = false;
      this.updateEchart();
    },
    generateMockData(days = 7, startDate = null, endDate = null) {
      const res = this.all_data || {};
      const allItems = [...(res.our_listing || []), ...(res.compete_listing || [])];
      const allProductNames = [...this.ourProductList, ...this.competeProductList].map(p => p.label);

      const result = [];
      let start, end;
      if (startDate && endDate) {
        start = new Date(startDate);
        end = new Date(endDate);
      } else {
        end = new Date();
        start = new Date();
        start.setDate(end.getDate() - (days - 1));
      }

      const allDates = [];
      const current = new Date(start);
      while (current <= end) {
        allDates.push(new Date(current));
        current.setDate(current.getDate() + 1);
      }

      let displayDates = allDates;
      if (allDates.length > 30) {
        const step = Math.floor((allDates.length - 1) / 29);
        const selected = [];
        for (let i = 0; i < 29; i++) {
          selected.push(allDates[i * step]);
        }
        selected.push(allDates[allDates.length - 1]);
        displayDates = selected;
      }

      displayDates.forEach(date => {
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const shortDate = `${month}-${day}`;
        const year = date.getFullYear();
        const fullDate = `${year}-${month}-${day}`;
        const row = { date: shortDate };

        allProductNames.forEach(product => {
          const matchItem = allItems.find(item => {
            const key = item.paltfrom_sku
              ? `${item.paltfrom_sku}--${item.listing_id}`
              : `竞品--${item.listing_id}`;
            return key === product;
          });

          const history = matchItem?.history_json?.[fullDate] || { gmv: 0, price: 0, sales: 0 };

          row[product] = {
            sales: history.sales || 0,
            gmv: history.gmv || 0,
            price: parseFloat(history.price || 0),
            stock: matchItem?.estimated_available_quantity || 0
          };
        });

        result.push(row);
      });

      this.chartData = result;
      this.updateEchart();
    },
    updateEchart() {
      const dates = this.chartData.map(i => i.date);
      this.dateRangeTip = dates.length > 0 ? `${dates[0]} 至 ${dates[dates.length - 1]}` : '';

      const series = this.selectedProducts.map((productName, index) => {
        const data = this.chartData.map(day => day[productName]?.[this.currentField] || 0);
        
        console.log("productName==>", productName)
        const colors = ['#5470C6', '#91CC75',  '#FAC858', '#73C0DE', '#3BA272'];
        return {
          name: productName,
          type: this.chartType,
          data,
          smooth: this.chartType === 'line',
          itemStyle: { color: productName.includes('竞品')? '#EE6666' : colors[index % colors.length] }
        };
      });

      this.chartOptions = {
        tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
        legend: {
          data: this.selectedProducts,
          top: 25,
          left: 'center',
          textStyle: { fontSize: 14 }
        },
        grid: { top: '60px', left: '60px', right: '60px', bottom: '50px' },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: { rotate: 45, interval: 0 }
        },
        yAxis: {
          type: 'value',
          name: this.dataFields[this.currentField],
          axisLine: { lineStyle: { color: '#5470C6' } }
        },
        series
      };
    }
  }
};
</script>

<style scoped></style>
